<template>
  <!-- 定时发布设置弹窗 -->
  <my-dialog
    :dialog-state="props.regularRelease"
    :dialog-title="timePublishDialog.title"
    :dialog-width="timePublishDialog.width"
    :icon-type="timePublishDialog.default"
    :but-status="timePublishDialog.butStatus"
    @handleCancel="timePublishDialogCancel"
    @handleOk="timePublishDialogOk"
  >
    <template #location>
      <div class="time">
        <div class="tips">*</div>
        <div>有效期限：</div>
        <a-range-picker
          v-model:value="effectiveTime"
          format="YYYY-MM-DD"
          :disabled="formDayData.isForever ? true : false"
          :disabled-date="disabledDate"
          @change="onEffective"
          @ok="ok"
          @calendarChange="onCalendarChange"
        />
      </div>
      <div v-if="formDayData.isForever" class="time-slot">永久</div>
      <!-- <div v-else-if="dateOrWeek === 1 && formWeekData.isForever" class="time-slot">永久</div> -->
      <div v-else class="time-slot">{{ timeFn }}</div>
      <div class="permanent-switch">
        <div class="permanent">
          <div class="tips">*</div>
          发布时间：
          <div class="time-cycle">
            <div class="date" :class="dateOrWeek === 0 ? 'date-active' : null" @click="dayClick">
              天
            </div>
            <div class="date" :class="dateOrWeek === 1 ? 'date-active' : null" @click="weekClick">
              周
            </div>
          </div>
        </div>
      </div>
      <!-- 天 -->
      <div v-if="dateOrWeek === 0" class="tabs-week">
        <div v-for="(item, index) in dayForm" :key="item.index" class="tabs-week-time">
          <!-- <a-range-picker format=" HH:mm" value-format=" HH:mm" @change="dayTime(item, $event)" /> -->

          <a-time-range-picker
            v-model:value="item.timeNull"
            format="HH:mm"
            value-format=" HH:mm:ss"
            @change="dayTime(item, $event)"
          />
          <img
            v-if="index !== 0"
            src="../../assets/images/Upload_icon_dete.png"
            alt=""
            class="tabs-week-time-delete"
            @click="deleteTime(item, index)"
          />
        </div>
        <div class="add" :class="formDayData.id >= 5 ? 'no-add' : null" @click="addDay">
          <img src="../../assets/icons/images/popup_icon_add.png" alt="" />
        </div>
      </div>
      <!-- 周 -->
      <div v-else class="tabs-week">
        <div class="week-tabs">
          <div
            v-for="(item, index) in weekTabs"
            :key="item.id"
            :class="item.state ? 'week-tabs-active' : null"
            @click="weekTabsChange(index)"
          >
            {{ item.name }}
          </div>
        </div>
        <div
          v-for="(item, index) in weekTabs[weekIndex].data"
          :key="item.index"
          class="tabs-week-time"
        >
          <a-time-range-picker
            v-model:value="item.weekNull"
            format="HH:mm"
            value-format="HH:mm:ss"
            @change="weekTime(item, index, $event)"
          />
          <img
            v-if="index !== 0"
            src="../../assets/images/Upload_icon_dete.png"
            alt=""
            class="tabs-week-time-delete"
            @click="deleteWeek(item, index)"
          />
        </div>
        <div
          class="add"
          :class="weekTabs[weekIndex].data.length === 5 ? 'no-add' : null"
          @click="addWeek"
        >
          <img src="../../assets/icons/images/popup_icon_add.png" alt="" />
        </div>
      </div>
      <div class="permanent-switch">
        <div class="permanent">永久发布：</div>
        <a-switch v-model:checked="formDayData.isForever" @change="onForever" />
      </div>
      <!-- <div v-else class="permanent-switch">
        <div class="permanent">永久发布：</div>
        <a-switch v-model:checked="formWeekData.isForever" @change="changeForever" />
      </div> -->
    </template>
  </my-dialog>
</template>

<script setup>
import { Upload, Form, Message, Modal } from 'ant-design-vue';
import MyDialog from '@/components/dialog/index.vue';
import { LockFilled, PlusOutlined } from '@ant-design/icons-vue';
import { useRouter, useRoute } from 'vue-router';
import { videoMd5Verify, saveInfoVideoDraft, getInfoVideo, saveInfoVideo } from '@/api/user';
import moment from 'moment';
import dayjs from 'dayjs';
import { timeFns } from '../../util/OBSUpload';

import { ref, defineEmits, reactive, defineProps, onMounted, watch, defineExpose } from 'vue';

const props = defineProps({
  // 定时弹窗显示隐藏状态
  regularRelease: {
    type: Array,
    default: () => []
  },
  timingData: {
    type: Object,
    default: () => {}
  },
  timingState: {
    type: String
  }
});
function onForever() {
  if (formDayData.isForever === false) {
    effectiveTime.value = [];
    timeFn.value = '0天0时0秒';
    validPeriodStart.value = '';
    validPeriodStop.value = '';
  } else {
    if (validPeriodStart.value) {
      effectiveTime.value = [
        dayjs(validPeriodStart.value, 'YYYY-MM-DD HH:mm'),
        dayjs('9999-12-31 23:59:59', 'YYYY-MM-DD HH:mm')
      ];
    } else {
      effectiveTime.value = [
        dayjs(moment().format('YYYY-MM-DD HH:mm')),
        dayjs('9999-12-31 23:59:59', 'YYYY-MM-DD HH:mm')
      ];
    }
  }
  // if (props.timingData.infoBO.isForever === 1) {
  if (formDayData.isForever === false) {
    effectiveTime.value = [];
  }
  // } else {
  if (formDayData.isForever === true) {
    effectiveTime.value = [
      dayjs(moment().format('YYYY-MM-DD HH:mm')),
      dayjs('9999-12-31 23:59:59', 'YYYY-MM-DD HH:mm')
    ];
  }
  // }
}

// 转换时间戳
function getTimeFormat(timeS) {
  let time = new Date(timeS).getTime(); // 除1000 是变成秒级的时间戳 不除就是毫秒级
  return time;
}

function getDatas(data, value) {
  if (value === '1') {
    // 定时天1 ，定时周2
    if (data.infoBO.releaseOpportunityType === 1 || data.infoBO.releaseOpportunityType === 2) {
      if (data.infoBO.isForever === 1) {
        formDayData.isForever = true;
        effectiveTime.value = [
          dayjs(data.infoBO.validPeriodStart, 'YYYY-MM-DD HH:mm'),
          dayjs('9999-12-31 23:59:59', 'YYYY-MM-DD HH:mm')
        ];
      } else {
        formDayData.isForever = false;
        effectiveTime.value = [
          dayjs(data.infoBO.validPeriodStart, 'YYYY-MM-DD HH:mm'),
          dayjs(data.infoBO.validPeriodStop, 'YYYY-MM-DD HH:mm')
        ];
        validPeriodStart.value = data.infoBO.validPeriodStart;
        validPeriodStop.value = data.infoBO.validPeriodStop;
        // 时间差的毫秒数
        timeFn.value = timeFns(
          getTimeFormat(data.infoBO.validPeriodStart.slice(0, -9)),
          getTimeFormat(data.infoBO.validPeriodStop.slice(0, -9)),
          'identical'
        );
      }
    } else {
      effectiveTime.value = [];
    }

    // 按天的数组
    if (data.daySiteVOList !== undefined) {
      if (data.infoBO.isForever === 1) {
        formDayData.isForever = true;
        effectiveTime.value = [
          dayjs(data.infoBO.validPeriodStart, 'YYYY-MM-DD HH:mm'),
          dayjs('9999-12-31 23:59:59', 'YYYY-MM-DD HH:mm')
        ];
      } else {
        formDayData.isForever = false;
      }
      dateOrWeek.value = 0;
      let dayArr = [];
      data.daySiteVOList.forEach(item => {
        dayArr.push({
          counts: 0,
          newStartTime: item.newStartTime,
          newStopTime: item.newStopTime,
          timeNull: [dayjs(item.newStartTime, 'HH:mm'), dayjs(item.newStopTime, 'HH:mm')]
        });
      });
      dayForm.value = dayArr;
    }
    // 按周的数组
    if (data.weekSiteVOList !== undefined) {
      dateOrWeek.value = 1;
      if (data.infoBO.isForever === 1) {
        formDayData.isForever = true;
        effectiveTime.value = [
          dayjs(data.infoBO.validPeriodStart, 'YYYY-MM-DD HH:mm'),
          dayjs('9999-12-31 23:59:59', 'YYYY-MM-DD HH:mm')
        ];
      } else {
        formWeekData.isForever = false;
      }
      data.weekSiteVOList.forEach(elme => {
        weekTabs.value.forEach(item => {
          if (elme.dayWeek === Number(item.id)) {
            item.data = elme.daySiteBOList;
          }
        });
      });
      weekTabs.value.forEach(item => {
        item.data.forEach((items, index) => {
          items.id = index + 1;
          items.weekCounts = 0;
          items.weekNull =
            items.newStartTime === ''
              ? null
              : [dayjs(items.newStartTime, 'HH:mm'), dayjs(items.newStopTime, 'HH:mm')];
        });
      });
    }
  }
}
defineExpose({
  getDatas
});
// 限制不可选择之前得时间
function disabledDate(current) {
  return current && current < moment().subtract(1, 'days').endOf('day');
}
const emit = defineEmits(['handleCancel'], ['handleOks']);
const router = useRouter();
const route = useRoute();
function dayTime(data, e) {
  data.newStartTime = e[0].replace(/\s+/g, '');
  data.newStopTime = e[1].replace(/\s+/g, '');

  if (data.newStartTime === data.newStopTime) {
    Message.error('起止时间不能相等，请重新选择时间');
    data.timeNull = [];
  }
}
// 定时发布设置弹窗相关
const timePublishDialog = reactive({
  title: '定时发布设置',
  default: 'default',
  visible: props.regularRelease,
  butStatus: '确认发布',
  width: '545px'
});
let effectiveTime = ref([]); // 有效期
let validPeriodStart = ref(''); // 有效期开始
let validPeriodStop = ref(''); // 有效期结束
// week周数据
const formWeekData = reactive({
  releaseTime: [], // 发布时间
  newStartTime: '', // 发布开始时间
  newStopTime: '', // 发布结束时间
  isForever: false,
  id: 1
});
// day 天数据
const formDayData = reactive({
  releaseTime: [], // 发布时间
  newStartTime: '', // 发布开始时间
  newStopTime: '', // 发布结束时间
  isForever: false,
  id: 1
});
// 按周的时间数组
const weekForm = ref([
  {
    weekCounts: 0,
    newStartTime: '', // 开始时间
    newStopTime: '', // 结束时间
    weekNull: null // 解决删除时间页面同步的问题
  }
]);
// 按天的时间数组
const dayForm = ref([
  {
    counts: 0,
    newStartTime: '', // 开始时间
    newStopTime: '', // 结束时间
    timeNull: null // 解决删除时间页面同步的问题
  }
]);
const weekTabs = ref([
  {
    name: '一',
    id: '1',
    state: true,
    data: [
      {
        id: 1,
        weekCounts: 0,
        newStartTime: '', // 开始时间
        newStopTime: '', // 结束时间
        weekNull: null // 解决删除时间页面同步的问题
      }
    ]
  },
  {
    name: '二',
    id: '2',
    state: false,
    data: [
      {
        id: 1,
        weekCounts: 0,
        newStartTime: '', // 开始时间
        newStopTime: '', // 结束时间
        weekNull: null // 解决删除时间页面同步的问题
      }
    ]
  },
  {
    name: '三',
    id: '3',
    state: false,
    data: [
      {
        id: 1,
        weekCounts: 0,
        newStartTime: '', // 开始时间
        newStopTime: '', // 结束时间
        weekNull: null // 解决删除时间页面同步的问题
      }
    ]
  },
  {
    name: '四',
    id: '4',
    state: false,
    data: [
      {
        id: 1,
        weekCounts: 0,
        newStartTime: '', // 开始时间
        newStopTime: '', // 结束时间
        weekNull: null // 解决删除时间页面同步的问题
      }
    ]
  },
  {
    name: '五',
    id: '5',
    state: false,
    data: [
      {
        id: 1,
        weekCounts: 0,
        newStartTime: '', // 开始时间
        newStopTime: '', // 结束时间
        weekNull: null // 解决删除时间页面同步的问题
      }
    ]
  },
  {
    name: '六',
    id: '6',
    state: false,
    data: [
      {
        id: 1,
        weekCounts: 0,
        newStartTime: '', // 开始时间
        newStopTime: '', // 结束时间
        weekNull: null // 解决删除时间页面同步的问题
      }
    ]
  },
  {
    name: '日',
    id: '7',
    state: false,
    data: [
      {
        id: 1,
        weekCounts: 0,
        newStartTime: '', // 开始时间
        newStopTime: '', // 结束时间
        weekNull: null // 解决删除时间页面同步的问题
      }
    ]
  }
]);
let dateOrWeek = ref(0); // 0每天 1周
// 定时发布设置取消按钮
function timePublishDialogCancel() {
  emit('handleCancel', false);
}
// 定时发布设置确定按钮
let weekSite = ref([]);
function timePublishDialogOk() {
  let daySiteBOList = [];
  console.log(dateOrWeek.value);
  if (dateOrWeek.value === 1) {
    // 周
    let weekList = [];
    weekTabs.value.forEach((item, index) => {
      let daySiteBOList = [];
      item.data.forEach(items => {
        if (items.newStartTime !== '') {
          daySiteBOList.push({
            newStartTime: items.newStartTime,
            newStopTime: items.newStopTime
          });
          weekList.push({
            dayWeek: item.id,
            daySiteBOList: daySiteBOList
          });
        }
      });
      let obj = {};
      weekSite.value = weekList.reduce((newArr, next) => {
        obj[next.dayWeek] ? '' : (obj[next.dayWeek] = true && newArr.push(next));
        return newArr;
      }, []);
      return weekList;
    });
  } else {
    // 天
    dayForm.value.forEach(item => {
      if (item.newStartTime !== '') {
        daySiteBOList.push({
          newStartTime: item.newStartTime,
          newStopTime: item.newStopTime
        });
      }
    });
  }
  // 提示  ：注意天和周
  // 天
  let dayData = {
    releaseFrequency: dateOrWeek.value, // 发布频率 0每天 1每周
    effectiveTime: dayForm.value,
    validPeriodStart: validPeriodStart.value, // 有效期开始
    validPeriodStop: validPeriodStop.value, // 有效期结束
    isForever: formDayData.isForever, // 永久
    daySiteBOList: daySiteBOList // 天参数
  };
  // 周
  let weekData = {
    releaseFrequency: dateOrWeek.value, // 发布频率 0每天 1每周
    validPeriodStart: validPeriodStart.value, // 有效期开始
    validPeriodStop: validPeriodStop.value, // 有效期结束
    isForever: formDayData.isForever, // 永久
    weekSiteBOList: weekSite.value // 周参数
  };
  if (formDayData.isForever) {
    if (validPeriodStart.value) {
      dayData.validPeriodStart = validPeriodStart.value;
      weekData.validPeriodStart = validPeriodStart.value;
    } else {
      dayData.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss');
      weekData.validPeriodStart = moment().format('YYYY-MM-DD HH:mm:ss');
    }
    dayData.validPeriodStop = '9999-12-31 23:59:59';
    weekData.validPeriodStop = '9999-12-31 23:59:59';
  }
  console.log(444, dayData);
  console.log(555, weekData);
  emit('handleOks', dateOrWeek.value * 1 === 0 ? dayData : weekData);
}
let timeFn = ref('0天0时0秒');
// 有效期事件
function onEffective(date, dateString) {
  validPeriodStart.value = dateString[0] + ' 00:00:00';
  validPeriodStop.value = dateString[1] + ' 23:59:59';
  timeFn.value = timeFns(date[0], date[1], 'identical'); // 时间差的毫秒数
}
// 时间取消事件
function onCalendarChange() {
  timeFn.value = '0天0时0秒';
}
function dayClick() {
  dateOrWeek.value = 0;
}
function weekClick() {
  dateOrWeek.value = 1;
}
let weekIndex = ref(0); // 周的index
function weekTabsChange(index) {
  weekIndex.value = index;
  weekTabs.value.forEach(item => {
    item.state = false;
  });
  weekTabs.value[index].state = true;
}
// 按周删除事件
function deleteWeek(item, index) {
  weekTabs.value[weekIndex.value].data.splice(index, 1);
}
// 按周添加事件
function addWeek() {
  if (weekTabs.value[weekIndex.value].data.length < 5) {
    weekTabs.value[weekIndex.value].data.push({
      id: weekTabs.value[0].data[0].id++,
      weekNull: null,
      weekCounts: 0,
      newStartTime: '', // 开始时间
      newStopTime: '' // 结束时间
    });
  }
}
// 按周发布时间事件
function weekTime(item, index, dateString) {
  // 根据id找索引
  // let index = weekForm.value.findIndex(it => it.weekCounts === item.weekCounts);
  if (dateString != null) {
    item.newStartTime = dateString[0].replace(/\s+/g, '');
    item.newStopTime = dateString[1].replace(/\s+/g, '');
    if (item.newStartTime === item.newStopTime) {
      Message.error('起止时间不能相等，请重新选择时间');
      item.weekNull = [];
    }
  } else {
    item.newStartTime = '';
    item.newStopTime = '';
  }
}
// 添加天时间表单事件
function addDay() {
  if (formDayData.id < 5) {
    dayForm.value.push({
      counts: formDayData.id,
      newStartTime: '', // 开始时间
      newStopTime: '' // 结束时间
    });
    formDayData.id++;
  }
}
// 删除时间表单事件
function deleteTime(item) {
  // 过滤器
  dayForm.value = dayForm.value.filter(it => it.counts !== item.counts);
}
</script>
<style lang="less" scoped>
.time {
  display: flex;
  align-items: center;
  /deep/ .micro-ant-picker-range {
    width: 391px !important;
  }
  .tips {
    color: #ff0000;
    margin-right: 8px;
  }
  /deep/ .ant-picker-input > input {
    text-align: center !important;
  }
}
.time-slot {
  display: flex;
  justify-content: flex-end;
  margin-right: 23px;
  margin-top: 8px;
  font-size: 14px;
  color: #999999;
}
.permanent-switch {
  display: flex;
  margin-top: 25px;
  align-items: center;
  .permanent {
    display: flex;
    align-items: center;
    margin-right: 10px;
    .tips {
      color: #ff0000;
      margin-right: 8px;
    }
    .time-cycle {
      display: flex;
      .date {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 45px;
        height: 31px;
        border: 1px solid #d6aa56;
      }
      .date-active {
        background: #d6aa56;
        color: #ffffff;
      }
    }
  }
}
.tabs-week {
  margin-top: 23px;
  margin-left: 82px;
  .add {
    width: 391px;
    cursor: pointer;
    height: 36px;
    background: #ffffff;
    border: 1px solid #e1dddd;
    border-radius: 4px;
    img {
      width: 19px;
      height: 21px;
      margin: 6px auto;
    }
  }
  .no-add {
    cursor: no-drop;
  }
  .tabs-week-time {
    display: flex;
    align-items: center;
    margin-bottom: 23px;
    /deep/ .micro-ant-picker-range {
      width: 391px !important;
      height: 36px !important;
    }
    .tabs-week-time-delete {
      margin-left: 9.14px;
      cursor: pointer;
    }
  }
  .week-tabs {
    display: flex;
    align-items: center;
    margin-bottom: 23px;
    div {
      width: 44px;
      height: 32px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 100px;
    }
    .week-tabs-active {
      background: #f7eedd;
      color: #d6aa56;
    }
  }
}
/deep/ .micro-ant-picker-content {
  & > ul:nth-child(3) {
    display: none !important;
  }
}
</style>
